package makabakaquestionnaire.zutsoftware.exception.handler;

import lombok.extern.slf4j.Slf4j;
import makabakaquestionnaire.zutsoftware.constant.Result;
import makabakaquestionnaire.zutsoftware.enums.ExceptionCode;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 空指针异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！原因是:{}", e);
        return Result.failed("空指针异常");
    }

    /**
     * 插入或更新数据库，键值重复异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return Result.failed("数据库中已存在该记录");
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Object exceptionHandler(MissingServletRequestParameterException e) {
        log.error("System Exception:{}", e.getMessage());
        return Result.failed(e.getMessage());
    }

    //其他异常，异常的父类，没有子类就用它处理异常
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.failed("未知异常:" + e);
    }


}
